<template>
  <el-dialog
    v-model="dialogVisible"
    title="AI 妙笔"
    width="50%"
    destroy-on-close
    :append-to-body="true"
    :lock-scroll="false"
    :show-close="!isWriting"
    :before-close="handleBeforeClose"
  >
    <div class="space-y-4">
      <!-- 基础信息表单 -->
      <div v-show="!isWriting">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="88px" class="space-y-3">
          <el-form-item label="主题/标题" prop="title">
            <el-input v-model="form.title" placeholder="例如：关于推进××城区老旧小区改造的实施意见" />
          </el-form-item>
          <el-form-item label="参考资料" prop="abstract">
            <el-input v-model="form.abstractContent" type="textarea" :rows="4" placeholder="" />
          </el-form-item>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-form-item label="模型" prop="modelName" class="min-w-0">
              <el-select v-model="form.modelName" class="w-full">
                <el-option v-for="item in models" :label="item.name" :value="item.name" :key="item.id" />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-center items-center w-full py-4">
        <div class="flex items-center gap-4 justify-center">
          <div class="flex items-center gap-3">
            <template v-if="!isWriting">
              <el-button @click="onCancel" :disabled="startLoading">取 消</el-button>
              <el-button
                type="primary"
                :loading="startLoading"
                @click="startWriting"
              >开始写作</el-button>
            </template>
          </div>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { list as modelList } from '/@/api/knowledge/aiModel'

interface WritingFormData {
  title: string
  abstractContent: string
  modelName: string
  docTemplateId: string
  lockEditor: boolean
}

interface ModelItem {
  id: string
  name: string
}

// Props
interface Props {
  modelValue: boolean
  isWriting?: boolean
  startLoading?: boolean
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'start-writing', formData: WritingFormData): void
  (e: 'cancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  isWriting: false,
  startLoading: false,
})

const emit = defineEmits<Emits>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单相关
const formRef = ref<FormInstance>()
const form = reactive<WritingFormData>({
  title: '',
  abstractContent: '',
  modelName: '',
  docTemplateId: '',
  lockEditor: true,
})

const rules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
}

const models = ref<ModelItem[]>([])

// 暴露给父组件的方法
const openDialog = async (templateId: string) => {
  // 重置表单数据
  form.title = ''
  form.abstractContent = ''
  form.lockEditor = true
  form.docTemplateId = templateId

  // 获取模型列表
  const { data } = await modelList({ modelType: ['Chat'] })
  models.value = data
  if (data.length > 0) {
    form.modelName = data[0].name
  }
}

function onCancel() {
  emit('cancel')
}

function handleBeforeClose(done: () => void) {
  if (props.isWriting) {
    ElMessage.warning('正在生成中，请先停止')
    return
  }
  done()
}

async function startWriting() {
  await formRef.value?.validate()
  emit('start-writing', { ...form })
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>
